package com.swgk.core.common.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import org.greenrobot.eventbus.EventBus;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * @author: 杨畔
 * @date: 2021/2/20 15:23
 * @Description: fragment基类
 */
public abstract class BaseFragment<VM extends BaseViewModel, VDB extends ViewDataBinding>
        extends SupportFragment implements View.OnClickListener {

    private static final int MIN_CLICK_DELAY_TIME = 2000;
    //
    protected VM mViewModel = null;
    protected VDB mBinding;
    //
    private static long lastClickTime;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //初始化我们的binging
        mBinding = DataBindingUtil.inflate(inflater, layoutId(), container, false);
        //给binding加上感知生命周期
        mBinding.setLifecycleOwner(this);

        //创建我们的ViewModel
        createViewModel();
        init();
        //绑定EventBus
        if (isUseEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return mBinding.getRoot();
    }

    protected abstract int layoutId();

    protected abstract void createViewModel();
    /**
     * 初始化逻辑
     */
    protected abstract void init();
    /**
     * 是否使用eventBus
     */
    protected boolean isUseEventBus() {
        return false;
    }

    @Override
    public void onClick(View v) {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            lastClickTime = curClickTime;
            onMultiClick(v);
        }
    }

    /**
     * 防重点击
     */
    protected void onMultiClick(View v){

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解绑eventBus
        if (isUseEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
